import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
// import { Message } from 'element-ui'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 500000000000 // 超时时间
})

const time = 50000000000000 // token过期时间

// 请求拦截器
service.interceptors.request.use(config => {
  // console.log(101, config)
  const token = store.state.user.token
  if (token && config.url !== '/auth/local/register') {
    const curTime = Date.now()
    const loginTime = localStorage.getItem('loginTime')
    if (curTime - loginTime > time) {
      // token失效 退出登录
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('登录超时'))
    }
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

service.interceptors.response.use((response) => {
  // console.log(response)
  if (response.statusText) {
    return response
  } else {
    Message.error(response.message)
    return Promise.reject(new Error(response.message))
  }
}, (error) => {
  console.dir(error)
  Message.error(error.message)
  return Promise.reject(new Error(error))
}
)

// 导出axios实例
export default service
